package com.app.advice;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.util.SaResult;
import com.app.exception.BizException;
import com.app.result.CommonResult;
import com.app.result.CommonResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @author samir
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 数据库异常
     */
    @ExceptionHandler(DataAccessException.class)
    public CommonResult handleException(DataAccessException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return CommonResult.failed("数据库异常,请联系系统管理员");
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Throwable.class)
    public CommonResult handleException(Throwable e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return CommonResult.failed(e.getMessage());
    }

    /**
     * 登录验证异常
     */
    @ExceptionHandler(NotLoginException.class)
    public CommonResult handleBindException(NotLoginException e) {
        log.error(e.getMessage(), e);
        return CommonResult.failed(CommonResultCode.NOT_AUTH, e.getMessage());
    }

    /**
     * 登录验证异常
     */
    @ExceptionHandler(BizException.class)
    public CommonResult handleBindException(BizException e) {
        log.error(e.getMessage(), e);
        return CommonResult.failed(e.getCode() != null ? e.getCode() : 400, e.getMessage());
    }

    /**
     * sa-toke权限验证异常
     * @param e
     * @return
     */
    @ExceptionHandler(NotPermissionException.class)
    public CommonResult handlerException(NotPermissionException e) {
        log.error(e.getMessage(), e);
        return CommonResult.failed(CommonResultCode.FORBIDDEN, CommonResultCode.FORBIDDEN.getMessage());
    }
}
